<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Ekstrak_model extends CI_Model{
	private $second_db;
	
	function __construct()
	{
		parent::__construct();
		$this->load->database('db_datawarehouse', TRUE);
	}
	
	function getEkstrak()
	{
		$query = $this->db->get('fact_sales');
		return $query->result_array();
	}
	
	function getLog($limit=FALSE,$offset=FALSE)
	{
		$this->load->database('default', TRUE);
		$this->db->limit($limit,$offset);
		$this->db->order_by('log_id','desc');
		$query = $this->db->get('tb_log');
		return $query->result_array();
	}
	
	function cleanTableLog($table)
	{
		$this->load->database('default', TRUE);
		return $this->db->query("TRUNCATE TABLE $table");
	}
	
	function cleanTable($table)
	{
		$this->load->database('db_datawarehouse', TRUE);
		return $this->db->query("TRUNCATE TABLE $table");
	}

	function addLog($data)
	{
		$this->load->database('default', TRUE);
		$this->db->insert('tb_log',$data);
	}
	
	function loadTable($table,$data)
	{
		$this->load->database('db_datawarehouse', TRUE);
		$this->db->insert($table,$data);
	}

	function backupDb($th)
	{
		$host = "localhost";
		$user = "root";
		$pass = "";
		$database = "dbdemankcomp_dw";

		if($th != 'no')
		{
			$back = backupDB($host,$user,$pass,$database,$tables = '*',$th);// from helper 
			$date = date('d-M-Y-His');
			$handle = fopen('public/db/backup_dw_th_'.$th.'onserver-'.$date.'.sql','w+');
			  fwrite($handle,$back);
			  fclose($handle);
			$file_name = 'backup_dw_th_'.$th.'-'.$date.'.sql';
			$user = $this->session->userdata('user_display_name');
			$date = date("Y-m-d h:i:s");
			$data = array(
								'log_user'=>$user,
								'log_desc'=>'Backup datawarehose db '.$file_name,
								'log_date'=>$date
								);
			$this->addLog($data);
			$this->load->helper('download');
			force_download($file_name,$back); 
		}
		else
		{			
			redirect('backend/ekstrak/advanced');
		}

	}
	
	function importDb($filename)
	{
		$host = "localhost";
		$user = "root";
		$pass = "";
		$database = "dbdemankcomp_dw";
		
		mysql_connect($host, $user, $pass);
		mysql_select_db($database);

		$templine = '';
		$lines = file($filename);
		foreach ($lines as $line_num => $line)
		{
			if (substr($line, 0, 2) != '--' && $line != '')
				$templine .= $line;
			if (substr(trim($line), -1, 1) == ';')
			{
				mysql_query($templine);
				$templine = '';
			}
		}
	}
	
	
}

